<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/23
 * Time: 15:21
 */

namespace app\controllers;

use app\models\ExchangeModel;
use yii;

class ExchangeController extends ApiBaseController
{
    use \app\lib\Redis;

    public function actionList()
    {
        $model = new ExchangeModel();
        $list  = $model->all();
        return \json_encode(['list' => $list]);
    }

    public function actionUpdate()
    {
        if (!yii::$app->request->isPost) {
            return \json_encode(['code' => 0, 'msg' => 'not allowed']);
        }

        $id     = yii::$app->request->post('id', '');
        $column = yii::$app->request->post('column', '');
        $value  = yii::$app->request->post('value', '');
        if (!is_numeric($id)) {
            return \json_encode(['code' => 0, 'msg' => '数据错误']);
        }
        $model = new ExchangeModel();
        $re    = $model->save([$column => $value], ['id' => $id]);
        if ($re) {
            //清除缓存
            $this->getInstance()->delete('exchange:rate');
            return \json_encode(['code' => 1, 'msg' => '添加成功']);
        } else {
            return \json_encode(['code' => 0, 'msg' => '添加失败,请重试']);
        }
    }

    public function actionAdd()
    {
        if (!yii::$app->request->isPost) {
            return \json_encode(['code' => 0, 'msg' => 'not allowed']);
        }
        $data                 = [];
        $data['month']        = yii::$app->request->post('month');
        $data['rate']         = yii::$app->request->post('rate');
        $data['account_rate'] = yii::$app->request->post('account_rate');
        $model                = new ExchangeModel();
        $re                   = $model->insert($data);
        if ($re) {
            //清除缓存
            $this->getInstance()->delete('exchange:rate');
            return \json_encode(['code' => 1, 'msg' => '添加成功']);
        } else {
            return \json_encode(['code' => 0, 'msg' => '添加失败,请重试']);
        }
    }
}
